/*
 * @Author: Wushiqi
 * @Descripttion: 路由守卫、axios请求和响应拦截配置
 * @Date: 2020-08-12 17:34:42
 * @LastEditor: Wushiqi
 * @LastEditTime: 2020-12-21 15:31:42
 */
import router from './router'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条样式
import store from './store'
import axios from 'axios'
import { messageAlert } from '@/common/Message'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const menuList = store.getters.menuList
// const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  const csrf = sessionStorage._csrf // 获取csrf
  NProgress.start() // 进度条
  if (csrf) {
    if (to.path === '/login') {
      sessionStorage.clear()
      next()
      NProgress.done()
    } else {
      if (menuList) {
        next()
      } else {
        try {
          next({ path: '/' })
        } catch (error) {
          sessionStorage.clear()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
    if (!to.redirectedFrom && to.path !== '/redirect') { // 如果不是重定向操作，就存下当前访问的路由地址
      const paths = to.path.split('/')
      const path = paths[paths.length - 1]
      sessionStorage.setItem('toPath', path)
    }
  } else {
    if (to.path === '/login') {
      sessionStorage.clear()
      next()
    } else {
      // next(`/login?redirect=${to.path}`)
      next(`/login`)
      sessionStorage.clear()
      NProgress.done()
    }
  }
})

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  // const targetPath = router.history.pending.fullPath
  if (isChunkLoadFailed) {
    // router.replace(targetPath)
    location.reload()
  }
})

// request拦截器
axios.interceptors.request.use(config => {
  return config
}, err => {
  return Promise.reject(err)
})

// response拦截器
axios.interceptors.response.use(response => {
  if (response.data.flag === undefined && response.data.length > 0) {
    setTimeout(() => {
      sessionStorage.clear()
      // window.location.href = '/login'
      router.push('/login')
      location.reload()
    }, 50)
  } else if (response.data.flag === 'error') {
    if (response.data.errcode === 4001001 || response.data.errcode === 4000000) {
      messageAlert(response.data.data, '错误提示', {
        confirmButtonText: '确定',
        type: 'warning',
        callback: () => {
          sessionStorage.clear()
          router.push('/login')
        }
      })
    }
  }
  if (response.data.data === '12101001') {
    sessionStorage.clear()
    setTimeout(() => {
      router.push('/login')
    }, 50)
    return Promise.reject('error')
  } else {
    return response
  }
}, error => {
  let result = ''
  let flag = false
  if (String(error).indexOf('Network Error') !== -1) {
    result = '请求失败，请检查服务器或者重新登录' + '\n' + error
    flag = false
  } else if (String(error).indexOf('ERR_CONNECTION_REFUSED') !== -1) {
    result = '请求失败，请尝试重新登录' + error
    flag = false
  } else {
    result = error + ''
    flag = false
  }
  if (error.response) {
    const code = error.response.status
    if (code === 403) {
      if (error.response.data.data) {
        result = error.response.data.data
        flag = true
      } else {
        result = '没有权限,请尝试重新登录'
        flag = false
      }
    } else if (code === 500) {
      result = '服务器错误\n' + error.response.data.error
      flag = false
    } else if (code === 400) {
      result = '参数请求错误\n' + error.response.data.message
      flag = false
    } else if (code === 404) {
      result = '访问的地址不存在\n' + error.response.data.path
      flag = false
    }
  }
  messageAlert(result, '错误提示', {
    confirmButtonText: '确定',
    type: 'warning',
    callback: () => {
      if (flag) {
        sessionStorage.clear()
        router.push('/login')
      }
    }
  })
  return Promise.reject(result)
})

router.afterEach(() => {
  NProgress.done()
})
